const dialog  = require('electron').remote.dialog
const fs = require('fs')
var xml2js = require('xml2js');
const path = require('path')
var JSZip = require('jszip');

const { clipboard } = require('electron')

var parser = new xml2js.Parser();




function buildData(data){

    let _data = data;

    data = data.replace(new RegExp("<adi:OpenGroupAsset",'g'),"###<adi:OpenGroupAsset")
    .replace(new RegExp("<adi:AddMetadataAsset",'g'), "###<adi:AddMetadataAsset")
    .replace(new RegExp("<adi:AcceptContentAsset",'g'), "###<adi:AcceptContentAsset")
    .replace(new RegExp("<adi:AssociateContent",'g'), "###<adi:AssociateContent")
    .replace(new RegExp("<adi:AssociateGroup",'g'), "###<adi:AssociateGroup")
    .replace(new RegExp("</adi:ADI2>",'g'), "");
    console.log(data)
    const splitArray = data.split("###");
    const groupTitle = splitArray[0] + "\r\n" + splitArray[1] + "\r\n";
    parser.parseString(_data,function (err, result) {
        const root = result['adi:ADI2'];
        const associateContentList = root['adi:AssociateContent'];
        const associateGroupList = root['adi:AssociateGroup'];
        const orgID = associateGroupList[0]['$']['targetGroupAssetID'];

        let metadataTitle = "";
        for (const key in splitArray) {
            const groupID = splitArray[key]
            if(groupID.indexOf("AddMetadataAsset")>-1 && groupID.indexOf(orgID) >-1){
                metadataTitle = metadataTitle + "\r\n" + groupID + "\r\n";
            }
        }
        let allList = [];
        console.log(associateContentList);
        for (const key in associateContentList) {
            let fileStr = [];
            let type = associateContentList[key]['$']['type'];
            let groupID = associateContentList[key]['$']['groupAssetID'];
            let contentID = associateContentList[key]['$']['assetID'];
            for (const key in splitArray) {
                let str = splitArray[key];
                if(str.indexOf("OpenGroupAsset")>-1 && str.indexOf(groupID) >-1){
                    if("Image"==type){
                        str="";
                    }
                    fileStr[0]=(str);
                }
                if(str.indexOf("AddMetadataAsset")>-1 && str.indexOf(groupID) >-1){
                    if("Image"==type){
                        str="";
                    }
                    if("Video"==type){
                        // debugger
                        // parser.parseString(str,function (err, result) {
                        //     console.log(result);
                        // })
                        // str = str.replace
                        // let exStr = str.substring(str.lastIndexOf('<vod:TitleFull>'));
                        // console.log(exStr);

                        let name = str.substring(str.lastIndexOf('<vod:TitleFull>')+15,
                            str.lastIndexOf('</vod:TitleFull>'));
                        let oldName = name;
                        name =name.replace('_','-');
                        str  = str.replace(oldName,name);
                    }
                    
                    fileStr[1]=str;
                }
                if(str.indexOf("AcceptContentAsset")>-1 && str.indexOf(contentID) >-1){
                    fileStr[2]=str;
                }
                if(str.indexOf("AssociateContent")>-1 && str.indexOf(contentID) >-1){
                    fileStr[3]=str;
                }
                if(str.indexOf("AssociateGroup")>-1 && str.indexOf(groupID) >-1){
                    if("Image"==type){
                        str="Image";
                    }
                    fileStr[4]=str;
                }
            }
            allList.push(fileStr);
        }
        let one = allList.find((val)=>{console.log(val); return val[4]!="Image"});
        // let image = allList.find((val)=>{console.log(val); return val[4]=="Image"});
        let images = allList.filter((val)=>{return val[4]=="Image"});
        images.forEach((image)=>{
            one[2]=one[2] + "\r\n" +image[2];
            one[3]=one[3] + "\r\n" +image[3];
        });
        console.log(one)
        let arr = allList.filter((val)=>{
            return val[4]!="Image";
        })


        var zip = new JSZip();
        arr.forEach((val,i)=>{
            let fileName = (i > 9 ? "" + i : "0" + i) + ".xml";
            let content = groupTitle + val[0]+"\r\n" + metadataTitle + val[1] +"\r\n" + val[2] +"\r\n" + val[3] +"\r\n" + val[4] +"</adi:ADI2>";
            let file = path.resolve(__dirname, './tmp/'+fileName)
            zip.file(fileName,content);
            // fs.writeFile(file, content, { encoding: 'utf8' }, err => {})
        })
        // 压缩
        zip.generateAsync({
            // 压缩类型选择nodebuffer，在回调函数中会返回zip压缩包的Buffer的值，再利用fs保存至本地
            type: "nodebuffer",
            // 压缩算法
            compression: "DEFLATE",
            compressionOptions: {
                level: 9
            }
        }).then(function (content) {
            
            const _path = path.dirname(__dirname)+path.sep+"tmp"+path.sep;
            const file = _path+new Date().getTime() + '.zip';

            dialog.showSaveDialog({
                title:"保存文件",
                defaultPath:new Date().getTime() + '.zip',
                message:"请以.zip为后缀结尾"
            }).then(result=>{
                completeLoading();
                if(result.filePath){
                    // 写入磁盘
                    fs.writeFile(result.filePath, content, function (err) {
                        if (!err) {
                            alert("拆分成功");
                        } else {
                            dialog.showErrorBox("失败", "拆分失败");
                            console.log(err);

                        }
                    });
                }
            }).catch(error=>{
                dialog.showErrorBox("失败", "打包失败");
            });
            
        });
    });



    
    
}



var currentFilePath=''
window.onload = function(){
    const selectFile = this.document.querySelector('#selectFile')
    const split = this.document.querySelector('#split')
    const filePathVal = this.document.querySelector('#filePathVal')
    selectFile.onclick=()=>{
        dialog.showOpenDialog(
            { 
                title:'请选择拆分的文件',
                filters:[
                    { name: 'xml', extensions: ['xml'] },
                ],
            }
        ).then(res => {
            console.log(res.canceled)
            console.log(res.filePaths)
            // filePathVal.textContent=res.filePaths
            currentFilePath=res.filePaths[0]
            filePathVal.innerHTML="....../"+path.basename(currentFilePath);
        })
    }

    split.onclick=()=>{
        if(currentFilePath){
            fs.readFile(currentFilePath,'utf-8',(error,data)=>{
                showLoading();
                buildData(data)
            })
        }
    }

}
function copyFilePath(){
    if(currentFilePath){
        clipboard.writeText(currentFilePath)
    }
}



//在页面未加载完毕之前显示的loading Html自定义内容
var _LoadingHtml = '<div id="loadingDiv" style="display: none; "><div id="over" style=" position: absolute;top: 0;left: 0; width: 100%;height: 100%; background-color: #f5f5f5;opacity:0.5;z-index: 1000;"></div><div id="layout" style="position: absolute;top: 40%; left: 40%;width: 20%; height: 20%;  z-index: 1001;text-align:center;"><img src="asset/5-121204193955-51.gif" /></div></div>';
//呈现loading效果
document.write(_LoadingHtml);
 
//移除loading效果
function completeLoading() {  
		document.getElementById("loadingDiv").style.display="none";
}
//展示loading效果
function showLoading()
{
document.getElementById("loadingDiv").style.display="block";
}
